/**
 * [LupMisNotAllowedSync]
 * 本代码为系统自动生成代码，请根据自己业务进行修改;
 * 生成时间 2022-02-02 11:18:21;
 * 版权所有 2020-2022 lizhongwen，并保留所有权利;
 * 说明: 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用；不允许对程序代码以任何形式任何目的的再发布;
 * 作者: 中文Lee;
 * 作者主页: http://www.lizhongwen.com;
 * 邮箱: 360811363@qq.com;
 * QQ: 360811363;
 */

var table, $, form;

function $init(callback, isLoading = true) {
    layui.use(['layer', 'table', 'form'], function() {
        table = layui.table;
        $ = layui.$;
        form = layui.form;
        document.onkeydown = function(e) { // 键盘按键控制
            e = e || window.event;
            if ((e.ctrlKey && e.keyCode == 82) || e.keyCode == 116) {
                // F5刷新，禁止
                window.parent.$("#refresh").click();
                return false;
            }
            if ((e.ctrlKey && e.keyCode == 39)) {
                $(".layui-laypage-next i").click();
            }
            if ((e.ctrlKey && e.keyCode == 37)) {
                $(".layui-laypage-prev i").click();
            }
        }
        ajaxStart();
        //统一给ajax请求加header参数
        ajaxSend();
        //截获ajax参数
        ajaxSetup();
        clickCheckRow();
        if (callback()) {
            callback();
        }
    });
}

function replaceUrl(url) {
    return url.replace("//", "/");
}

function ajaxStart() {
    var loading;
    layui.$(document).ajaxStart(function() {
        loading = layer.load(2);
    }).ajaxStop(function() {
        layui.layer.closeAll('loading');
        setTimeout(function() { layui.layer.closeAll('loading'); }, 100);
    }).ajaxError(function(ret) {
        layer.msg('系统繁忙！');
        layui.layer.closeAll('loading');
        setTimeout(function() { layui.layer.closeAll('loading'); }, 100);
        setTimeout(function() {
            $(".layui-btn-disabled").removeClass('layui-btn-disabled');
        }, 1500);
    });
}

function ajaxSend() {
    layui.$(document).ajaxSend(function(event, jqxhr, settings) {
        jqxhr.setRequestHeader("accessuid", localStorage.getItem("accessuid"));
        jqxhr.setRequestHeader("accesstoken", localStorage.getItem("accesstoken"));
    });
}

function ajaxSetup() {
    layui.$.ajaxSetup({
        complete: function(xhr, status) {
            layui.layer.closeAll('loading');
            setTimeout(function() { layui.layer.closeAll('loading'); }, 100);
            var ret = JSON.parse(xhr.responseText);
            if (ret.code == 401) {
                localStorage.setItem("accesstoken", '');
                localStorage.setItem("accessuid", '');
                window.location.href = project_path + "login.html";
            } else if (ret.code == 403) {
                layer.msg(ret.msg);
                return false;
            }
        }
    });
}


function getLocalDictData() {
    var dictDataList = localStorage.getItem("dictDataList");
    return eval('(' + dictDataList + ')');
}

function getDictDataContent(dictCode, dictValue) {
    var dictDataList = localStorage.getItem("dictDataList");
    var arr = eval('(' + dictDataList + ')');
    var data = arr[dictCode];
    var val = "";
    for (var i = 0; i < data.length; i++) {
        if (data[i].dictValue == dictValue) {
            val = data[i].dictLabel;
            break;
        }
    }
    return val;
}

function getDictDataValueByLabel(dictCode, dictLabel) {
    var dictDataList = localStorage.getItem("dictDataList");
    var arr = eval('(' + dictDataList + ')');
    var data = arr[dictCode];
    var val = "";
    for (var i = 0; i < data.length; i++) {
        if (data[i].dict_label == dictLabel) {
            val = data[i].dict_value;
            break;
        }
    }
    return val;
}

function initDictData(action,callback) {
    var dictDataList = getLocalDictData();
    $(".dict-select").each(function(index, element) {
        var dictCode = $(this).attr("dict-code");
        var tips = $(this).attr("tips");
        var selectedValue = $(this).attr("selected-value") || "";
        var optionStr = "<option value=''>" + tips + "</option>";
        var dictData = dictDataList[dictCode] || [];
        for (var i = 0; i < dictData.length; i++) {
            var selected = "";
            if (selectedValue == dictData[i].dict_value) {
                selected = "selected";
            }
            if (dictData[i].is_default == 1 && action == 'add') {
                selected = "selected";
            }
            optionStr += "<option value='" + dictData[i].dict_value + "' " + selected + ">" + dictData[i].dict_label + "</option>";
        }
        $(this).html(optionStr);
        layui.form.render("select", null);
    });
    $(".dict-xmSelectNoPage").each(function(index, element) {
        var id = $(this).attr("id");
        var name = $(this).attr("name");
        var dictCode = $(this).attr("dict-code");
        var layVerify = $(this).attr("lup-lay-verify") || "";
        var layReqText = $(this).attr("lay-reqtext") || "必填项不能为空！";
        var tips = $(this).attr("tips");
        var selectedValue = $(this).attr("selected-value") || "";
        var dictData = dictDataList[dictCode] || [];
        var xmSelectData = [];
        for (var i = 0; i < dictData.length; i++) {
            var item = {
                name: dictData[i].dict_label,
                value: dictData[i].dict_value
            };
            xmSelectData.push(item);
        }
        var xmSelectObj = xmSelect.render({
            el: '#' + id,
            radio: true,
            clickClose: true,
            height: '300px',
            autoRow: true,
            filterable: true,
            tips: tips,
            name: name,
            layVerify: layVerify,
            layReqText: layReqText,
            layVerType: 'msg',
            on: function(data){
                if(callback){
                    callback(id,data);
                }
            },
            data: xmSelectData
        });
        xmSelectObj.setValue([selectedValue]);
    });
    $(".dict-xmMultiSelectNoPage").each(function(index, element) {
        var id = $(this).attr("id");
        var name = $(this).attr("name");
        var dictCode = $(this).attr("dict-code");
        var layVerify = $(this).attr("lup-lay-verify") || "";
        var layReqText = $(this).attr("lay-reqtext") || "必填项不能为空！";
        var tips = $(this).attr("tips");
        var selectedValue = $(this).attr("selected-value") || "";
        var dictData = dictDataList[dictCode] || [];
        var xmSelectData = [];
        for (var i = 0; i < dictData.length; i++) {
            var item = {
                name: dictData[i].dict_label,
                value: dictData[i].dict_value
            };
            xmSelectData.push(item);
        }
        var xmSelectObj = xmSelect.render({
            el: '#' + id,
            radio: false,
            clickClose: false,
            height: '300px',
            autoRow: true,
            filterable: true,
            tips: tips,
            name: name,
            layVerify: layVerify,
            layReqText: layReqText,
            layVerType: 'msg',
            on: function(data){
                if(callback){
                    callback(id,data);
                }
            },
            data: xmSelectData
        });
        var selectArr = selectedValue.split(",") || [];
        xmSelectObj.setValue(selectArr);
    });
    $(".dict-radio").each(function(index, element) {
        var dictCode = $(this).attr("dict-code");
        var name = $(this).attr("name");
        var tips = $(this).attr("tips");
        var layReqtext = $(this).attr("lay-reqText");
        var layVerify = $(this).attr("lup-lay-verify");
        var selectedValue = $(this).attr("selected-value") || "";
        var radioStr = "";
        var dictData = dictDataList[dictCode] || [];
        for (var i = 0; i < dictData.length; i++) {
            var checked = "";
            if (selectedValue == dictData[i].dict_value) {
                checked = "checked";
            }
            if (dictData[i].is_default == 1 && action == 'add') {
                checked = "checked";
            }
            radioStr += "<input type='radio' lay-verify='" + layVerify + "' lay-reqtext='" + layReqtext + "'  name='" + name + "' title='" + dictData[i].dict_label + "' value='" + dictData[i].dict_value + "' " + checked + " />";
        }
        $(this).html(radioStr);
        layui.form.render("radio", null);
    });
    $(".dict-checkbox").each(function(index, element) {
        var dictCode = $(this).attr("dict-code");
        var name = $(this).attr("name");
        var tips = $(this).attr("tips");
        var layReqtext = $(this).attr("lay-reqtext");
        var layVerify = $(this).attr("lup-lay-verify");
        var selectedValue = $(this).attr("selected-value") || "";
        var selectedValueArr = selectedValue.split(",");
        var checkboxStr = "<input type='hidden' name='" + name + "' value='" + selectedValue + "'>";
        var dictData = dictDataList[dictCode] || [];
        for (var i = 0; i < dictData.length; i++) {
            var checked = "";
            if (selectedValueArr.indexOf(dictData[i].dict_value) != -1) {
                checked = "checked";
            }
            checkboxStr += "<input type='checkbox' name='_" + name + "' lay-filter='" + name + "' lay-verify='" + layVerify + "' lay-reqtext='" + layReqtext + "'  class='checkbox_" + name + "' title='" + dictData[i].dict_label + "' value='" + dictData[i].dict_value + "' " + checked + " lay-skin='primary'/>";
        }
        $(this).html(checkboxStr);
        layui.form.render("checkbox", null);
        //监听checkbox选择
        layui.form.on('checkbox(' + name + ')', function(data) {
            var valArr = [];
            $(".checkbox_" + name).each(function(index, element) {
                var isCheck = $(this).prop('checked');
                if (isCheck) {
                    valArr.push($(this).val());
                }
            });
            $("input[name='" + name + "']").val(valArr);
        });
    });
}
//格式化树数据
function toTreeData(data, apiPid) {
    var pos = {};
    var tree = [];
    var i = 0;
    while (data.length != 0) {
        if (data[i].pid == apiPid) {
            tree.push({
                id: data[i].id,
                name: data[i].name,
                value: data[i].value,
                children: []
            });
            pos[data[i].id] = [tree.length - 1];
            data.splice(i, 1);
            i--;
        } else {
            var posArr = pos[data[i].pid];
            if (posArr != undefined) {
                var obj = tree[posArr[0]];
                for (var j = 1; j < posArr.length; j++) {
                    obj = obj.children[posArr[j]];
                }
                obj.children.push({
                    id: data[i].id,
                    name: data[i].name,
                    value: data[i].value,
                    children: []
                });
                pos[data[i].id] = posArr.concat([obj.children.length - 1]);
                data.splice(i, 1);
                i--;
            }
        }
        i++;
        if (i > data.length - 1) {
            i = 0;
        }
    }
    return tree;
}

function initTreeParentData(action) {
    //下拉树
    $(".tree-parent-xmSelectNoPage").each(function(index, element) {
        var tips = $(this).attr("tips");
        var api = $(this).attr("api");
        var cut = $(this).attr("cut");
        var key = $(this).attr("key");
        var name = $(this).attr("name");
        var val = $(this).attr("val");
        var pid = $(this).attr("pid") || "0";
        var valueArr = val.split(",");
        var selectedValue = $(this).attr("selected-value");
        var id = $(this).attr("id");
        var layVerify = $(this).attr("lup-lay-verify") || "";
        var layReqText = $(this).attr("lay-reqtext") || "必填项不能为空！";
        request(base_gateway + replaceUrl(api), { pid: pid }, function(ret) {
            var data = ret.data || [];
            var xmSelectData = [];
            for (var i = 0; i < data.length; i++) {
                var _vArr = [];
                for (var j = 0; j < valueArr.length; j++) {
                    _vArr[j] = data[i][valueArr[j]];
                }
                var selected = "";
                if (selectedValue == data[i][key]) {
                    selected = "selected";
                }
                var item = {
                    id: data[i].id,
                    name: _vArr.join(cut),
                    value: data[i][key],
                    pid: data[i]['pid']
                };
                xmSelectData.push(item);
            }

            data = xmSelectData;
            var treeList = toTreeData(data, pid);
            var xmSelectObj = xmSelect.render({
                el: '#' + id,
                radio: true,
                clickClose: true,
                height: '300px',
                autoRow: true,
                filterable: true,
                tips: tips,
                name: name,
                layVerify: layVerify,
                layReqText: layReqText,
                layVerType: 'msg',
                tree: {
                    show: true,
                    showFolderIcon: true,
                    showLine: true,
                    indent: 20,
                    strict: false,
                    //是否开启极简模式
                    simple: false,
                    expandedKeys: false,
                },
                toolbar: {
                    show: false,
                    list: ['ALL', 'REVERSE', 'CLEAR']
                },
                data: function() {
                    return treeList;
                }
            });
            xmSelectObj.setValue([selectedValue]);
        });
    });
    //tree下拉多选无分页
    $(".tree-parent-xmMultiSelectNoPage").each(function(index, element) {
        var tips = $(this).attr("tips");
        var api = $(this).attr("api");
        var cut = $(this).attr("cut");
        var key = $(this).attr("key");
        var name = $(this).attr("name");
        var val = $(this).attr("val");
        var pid = $(this).attr("pid") || "0";
        var valueArr = val.split(",");
        var selectedValueArr = [];
        var selectedValue = "";
        if (action != 'search') {
            selectedValue = $(this).attr("selected-value") || [];
            if (selectedValue.length > 0) {
                selectedValueArr = selectedValue.split(",") || [];
            }
        }
        var id = $(this).attr("id");
        var layVerify = $(this).attr("lup-lay-verify") || "";
        var layReqText = $(this).attr("lay-reqtext") || "必填项不能为空！";
        request(base_gateway + replaceUrl(api), { pid: pid }, function(ret) {
            var data = ret.data.rows || ret.data || [];
            var xmSelectData = [];
            for (var i = 0; i < data.length; i++) {
                var _vArr = [];
                for (var j = 0; j < valueArr.length; j++) {
                    _vArr[j] = data[i][valueArr[j]];
                }
                var item = {
                    id: data[i].id,
                    name: _vArr.join(cut),
                    value: data[i][key],
                    pid: data[i]['pid']
                };
                xmSelectData.push(item);
            }
            data = xmSelectData;
            var treeList = toTreeData(data, pid);
            var xmSelectObj = xmSelect.render({
                el: '#' + id,
                // radio: true,
                // clickClose: true,
                height: '300px',
                autoRow: true,
                filterable: true,
                tips: tips,
                name: name,
                layVerify: layVerify,
                layReqText: layReqText,
                layVerType: 'msg',
                tree: {
                    show: true,
                    showFolderIcon: true,
                    showLine: true,
                    indent: 20,
                    strict: true,
                    //是否开启极简模式
                    simple: false,
                    expandedKeys: true,
                },
                toolbar: {
                    show: false,
                    list: ['ALL', 'REVERSE', 'CLEAR']
                },
                data: function() {
                    return treeList;
                }
            });
            xmSelectObj.setValue(selectedValueArr);
        });
    });
}

function initDbTableData(action,callback) {
    $(".db-table-select").each(function(index, element) {
        var that = this;
        var tips = $(this).attr("tips");
        var api = $(this).attr("api");
        var cut = $(this).attr("cut");
        var key = $(this).attr("key");
        var name = $(this).attr("name");
        var val = $(this).attr("val");
        var valueArr = val.split(",");
        var selectedValue = $(this).attr("selected-value");
        request(base_gateway + replaceUrl(api), { page: 1, limit: 1000 }, function(ret) {
            var data = ret.data.rows || ret.data || [];
            var optionStr = "<option value=''>" + tips + "</option>";
            for (var i = 0; i < data.length; i++) {
                var _vArr = [];
                for (var j = 0; j < valueArr.length; j++) {
                    _vArr[j] = data[i][valueArr[j]];
                }
                var selected = "";
                if (selectedValue == data[i][key]) {
                    selected = "selected";
                }
                optionStr += "<option value='" + data[i][key] + "' " + selected + ">" + _vArr.join(cut) + "</option>";
            }
            $(that).html(optionStr);
            form.render("select", null);
        });
    });

    $(".db-table-xmSelectNoPage").each(function(index, element) {
        var tips = $(this).attr("tips");
        var api = $(this).attr("api");
        var cut = $(this).attr("cut");
        var key = $(this).attr("key");
        var name = $(this).attr("name");
        var val = $(this).attr("val");
        var valueArr = val.split(",");
        var selectedValue = $(this).attr("selected-value");
        var id = $(this).attr("id");
        var layVerify = $(this).attr("lup-lay-verify") || "";
        var layReqText = $(this).attr("lay-reqtext") || "必填项不能为空！";
        request(base_gateway + replaceUrl(api), { page: 1, limit: 1000 }, function(ret) {
            var data = ret.data.rows || ret.data || [];
            var xmSelectData = [];
            for (var i = 0; i < data.length; i++) {
                var _vArr = [];
                for (var j = 0; j < valueArr.length; j++) {
                    _vArr[j] = data[i][valueArr[j]];
                }
                var selected = "";
                if (selectedValue == data[i][key]) {
                    selected = "selected";
                }
                var item = {
                    name: _vArr.join(cut),
                    value: data[i][key]
                };
                xmSelectData.push(item);
            }
            var xmSelectObj = xmSelect.render({
                el: '#' + id,
                radio: true,
                clickClose: true,
                height: '300px',
                autoRow: true,
                filterable: true,
                tips: tips,
                name: name,
                layVerify: layVerify,
                layReqText: layReqText,
                layVerType: 'msg',
                on: function(data){
                    if(callback){
                        callback(id,data);
                    }
                },
                data: xmSelectData
            });
            xmSelectObj.setValue([selectedValue]);
        });
    });
    $(".db-table-xmMultiSelectNoPage").each(function(index, element) {
        var tips = $(this).attr("tips");
        var api = $(this).attr("api");
        var cut = $(this).attr("cut");
        var key = $(this).attr("key");
        var val = $(this).attr("val");
        var valueArr = val.split(",");
        var selectedValue = $(this).attr("selected-value") || "";
        var id = $(this).attr("id");
        var name = $(this).attr("name");
        var layVerify = $(this).attr("lup-lay-verify") || "";
        var layReqText = $(this).attr("lay-reqtext") || "必填项不能为空！";
        request(base_gateway + replaceUrl(api), { page: 1, limit: 1000 }, function(ret) {
            var data = ret.data.rows || ret.data || [];
            var xmMultiSelectData = [];
            for (var i = 0; i < data.length; i++) {
                var _vArr = [];
                for (var j = 0; j < valueArr.length; j++) {
                    _vArr[j] = data[i][valueArr[j]];
                }
                var selected = "";
                if (selectedValue == data[i][key]) {
                    selected = "selected";
                }
                var item = {
                    name: _vArr.join(cut),
                    value: data[i][key]
                };
                xmMultiSelectData.push(item);
            }
            var xmMultiSelectObj = xmSelect.render({
                el: '#' + id,
                height: '300px',
                autoRow: true,
                filterable: true,
                tips: tips,
                name: name,
                layVerify: layVerify,
                layReqText: layReqText,
                layVerType: 'msg',
                toolbar: {
                    show: true,
                    list: ['ALL', 'REVERSE', 'CLEAR']
                },
                on: function(data){
                    if(callback){
                        callback(id,data);
                    }
                },
                data: xmMultiSelectData
            });
            var selectArr = selectedValue.split(",") || [];
            xmMultiSelectObj.setValue(selectArr);
        });
    });
    $(".db-table-xmSelect").each(function(index, element) {
        var tips = $(this).attr("tips");
        var api = $(this).attr("api");
        var cut = $(this).attr("cut");
        var key = $(this).attr("key");
        var name = $(this).attr("name");
        var val = $(this).attr("val");
        var valueArr = val.split(",");
        var selectedValue = $(this).attr("selected-value") || "";
        var id = $(this).attr("id");
        var search = $(this).attr("search") || "";
        var layVerify = $(this).attr("lup-lay-verify") || "";
        var layReqText = $(this).attr("lay-reqtext") || "必填项不能为空！";
        var setValue = $(this).attr("set-value");
        if (setValue) {
            setValue = decodeURIComponent(setValue);
            setValue = eval('(' + setValue + ')');
        }
        var pageSize = 20;
        var xmSelectObj = xmSelect.render({
            el: '#' + id,
            radio: true,
            clickClose: true,
            height: '300px',
            autoRow: true,
            paging: true,
            pageSize: pageSize,
            filterable: true,
            pageEmptyShow: false,
            pageRemote: true,
            tips: tips,
            name: name,
            layVerify: layVerify,
            layReqText: layReqText,
            layVerType: 'msg',
            on: function(data){
                if(callback){
                    callback(id,data);
                }
            },
            remoteMethod: function(val, cb, show, page) {
                var requestPars = {};
                requestPars['page'] = page;
                requestPars['limit'] = pageSize;
                requestPars['lup_action'] = 'search';
                var _searchArr = search.split(",");
                for (var _i = 0; _i < _searchArr.length; _i++) {
                    requestPars[_searchArr[_i]] = val;
                }
                //val: 搜索框的内容, 不开启搜索默认为空, cb: 回调函数, show: 当前下拉框是否展开, pageIndex: 当前第几页
                request(base_gateway + replaceUrl(api), requestPars, function(ret) {
                    var code = ret.code;
                    if (code == 200 && ret.data.rows.length > 0) {
                        var data = ret.data.rows;
                        var pageCount = ret.data.page_count;
                        var xmSelectData = [];
                        for (var i = 0; i < data.length; i++) {
                            var _vArr = [];
                            for (var j = 0; j < valueArr.length; j++) {
                                _vArr[j] = data[i][valueArr[j]];
                            }
                            var selected = false;
                            if (selectedValue == data[i][key]) {
                                selected = true;
                            }
                            var item = {
                                name: _vArr.join(cut),
                                value: data[i][key],
                                selected: selected
                            };
                            xmSelectData.push(item);
                        }
                        //回调需要两个参数, 第一个: 数据数组, 第二个: 总页码
                        cb(xmSelectData, pageCount);
                        if (!isEmpty(setValue)) {
                            var appendArr = [];
                            for (var i = 0; i < setValue.length; i++) {
                                //这里要循环
                                var _vArr = [];
                                for (var j = 0; j < valueArr.length; j++) {
                                    _vArr[j] = setValue[i][valueArr[j]];
                                }
                                var selectJson = {
                                    name: _vArr.join(cut),
                                    value: setValue[i][key]
                                };
                                appendArr.push(selectJson);
                            }
                            xmSelectObj.setValue(appendArr);
                        }
                    } else {
                        cb([], 0);
                    }
                });
            }
        });
    });
    $(".db-table-xmMultiSelect").each(function(index, element) {
        var tips = $(this).attr("tips");
        var api = $(this).attr("api");
        var cut = $(this).attr("cut");
        var key = $(this).attr("key");
        var name = $(this).attr("name");
        var val = $(this).attr("val");
        var valueArr = val.split(",");
        var selectedValue = $(this).attr("selected-value") || "";
        var id = $(this).attr("id");
        var search = $(this).attr("search") || "";
        var layVerify = $(this).attr("lup-lay-verify") || "";
        var layReqText = $(this).attr("lay-reqtext") || "必填项不能为空！";
        var setValue = $(this).attr("set-value");
        if (setValue) {
            setValue = decodeURIComponent(setValue);
            setValue = eval('(' + setValue + ')');
        }
        var pageSize = 20;
        var xmSelectObj = xmSelect.render({
            el: '#' + id,
            height: '300px',
            autoRow: true,
            paging: true,
            pageSize: pageSize,
            filterable: true,
            pageEmptyShow: false,
            pageRemote: true,
            tips: tips,
            name: name,
            layVerify: layVerify,
            layReqText: layReqText,
            layVerType: 'msg',
            on: function(data){
                if(callback){
                    callback(id,data);
                }
            },
            toolbar: {
                show: true,
                list: ['ALL', 'REVERSE', 'CLEAR']
            },
            remoteMethod: function(val, cb, show, page) {
                var requestPars = {};
                requestPars['page'] = page;
                requestPars['limit'] = pageSize;
                requestPars['lup_action'] = 'search';

                var _searchArr = search.split(",");
                for (var _i = 0; _i < _searchArr.length; _i++) {
                    requestPars[_searchArr[_i]] = val;
                }
                //val: 搜索框的内容, 不开启搜索默认为空, cb: 回调函数, show: 当前下拉框是否展开, pageIndex: 当前第几页
                request(base_gateway + replaceUrl(api), requestPars, function(ret) {
                    var code = ret.code;
                    if (code == 200 && ret.data.rows.length > 0) {
                        var data = ret.data.rows;
                        var pageCount = ret.data.page_count;
                        var xmSelectData = [];
                        for (var i = 0; i < data.length; i++) {
                            var _vArr = [];
                            for (var j = 0; j < valueArr.length; j++) {
                                _vArr[j] = data[i][valueArr[j]];
                            }
                            var selected = false;
                            selectedValueArr = selectedValue.split(",");
                            if (selectedValueArr.indexOf(data[i][key]) != -1) {
                                selected = true;
                            }
                            var item = {
                                name: _vArr.join(cut),
                                value: data[i][key],
                                selected: selected
                            };
                            xmSelectData.push(item);
                        }
                        //回调需要两个参数, 第一个: 数据数组, 第二个: 总页码
                        cb(xmSelectData, pageCount);
                        if (!isEmpty(setValue)) {
                            var appendArr = [];
                            for (var i = 0; i < setValue.length; i++) {
                                //这里要循环
                                var _vArr = [];
                                for (var j = 0; j < valueArr.length; j++) {
                                    _vArr[j] = setValue[i][valueArr[j]];
                                }
                                var selectJson = {
                                    name: _vArr.join(cut),
                                    value: setValue[i][key]
                                };
                                appendArr.push(selectJson);
                            }
                            xmSelectObj.setValue(appendArr);
                        }
                    } else {
                        cb([], 0);
                    }
                });
            }
        });
    });
    //单选按钮数据库
    $(".db-table-radio").each(function(index, element) {
        var that = this;
        var tips = $(this).attr("tips");
        var api = $(this).attr("api");
        var cut = $(this).attr("cut");
        var key = $(this).attr("key");
        var name = $(this).attr("name");
        var val = $(this).attr("val");
        var valueArr = val.split(",");
        var selectedValue = $(this).attr("selected-value");
        var layReqtext = $(this).attr("lay-reqtext");
        var layVerify = $(this).attr("lay-verify");
        request(base_gateway + replaceUrl(api), { page: 1, limit: 1000 }, function(ret) {
            var data = ret.data.rows || ret.data || [];
            var radioStr = "";
            for (var i = 0; i < data.length; i++) {
                var _vArr = [];
                for (var j = 0; j < valueArr.length; j++) {
                    _vArr[j] = data[i][valueArr[j]];
                }
                var checked = "";
                if (selectedValue == data[i][key]) {
                    checked = "checked";
                }
                radioStr += "<input type='radio' lay-verify='" + layVerify + "' lay-reqtext='" + layReqtext + "'  name='" + name + "' title='" + _vArr.join(cut) + "' value='" + data[i][key] + "' " + checked + " />";
            }
            $(that).html(radioStr);
            form.render("radio", null);
        });
    });
    //复选框数据库
    $(".db-table-checkbox").each(function(index, element) {
        var that = this;
        var tips = $(this).attr("tips");
        var api = $(this).attr("api");
        var cut = $(this).attr("cut");
        var key = $(this).attr("key");
        var name = $(this).attr("name");
        var val = $(this).attr("val");
        var valueArr = val.split(",");
        var selectedValue = $(this).attr("selected-value") || "";
        var selectedValueArr = selectedValue.split(",") || [];
        var layReqtext = $(this).attr("lay-reqtext");
        var layVerify = $(this).attr("lay-verify");
        request(base_gateway + replaceUrl(api), { page: 1, limit: 1000 }, function(ret) {
            var data = ret.data.rows || ret.data || [];
            var checkboxStr = "<input type='hidden' name='" + name + "' value='" + selectedValue + "'>";
            for (var i = 0; i < data.length; i++) {
                var _vArr = [];
                for (var j = 0; j < valueArr.length; j++) {
                    _vArr[j] = data[i][valueArr[j]];
                }
                var checked = "";
                if (selectedValueArr.indexOf(data[i][key]) != -1) {
                    checked = "checked";
                }
                checkboxStr += "<input type='checkbox' lay-filter='" + name + "' class='checkbox_" + name + "' name='_" + name + "' lay-verify='" + layVerify + "' lay-reqtext='" + layReqtext + "' title='" + _vArr.join(cut) + "' value='" + data[i][key] + "' " + checked + " lay-skin='primary'/>";
            }
            $(that).html(checkboxStr);
            form.render("checkbox", null);
            //监听checkbox选择
            form.on('checkbox(' + name + ')', function(data) {
                var valArr = [];
                $(".checkbox_" + name).each(function(index, element) {
                    var isCheck = $(this).prop('checked');
                    if (isCheck) {
                        valArr.push($(this).val());
                    }
                });
                $("input[name='" + name + "']").val(valArr);
            });
        });
    });
}

function listResData(value, cut, data) {
    var valueArr = value.split(",");
    data = data || [];
    listData = [];
    for (var i = 0; i < data.length; i++) {
        var dataArr = [];
        for (var j = 0; j < valueArr.length; j++) {
            dataArr[j] = data[i][valueArr[j]];
        }
        listData[i] = dataArr.join(cut);
    }
    return listData.join(",");
}

function listDictData(dictCode, dictValue, customStr) {
    var dictDataList = getLocalDictData();
    var dictData = dictDataList[dictCode] || "";
    if (isEmpty(dictData)) {
        if (customStr) {
            return customStr;
        }
        return "";
    }
    if (dictValue == "") {
        return customStr || "";
    }
    var dictValueStr = "" + dictValue + "";
    var dictValueArr = dictValueStr.split(",");
    if (dictValueArr.length > 1) {
        var str = [];
        for (var i = 0; i < dictData.length; i++) {
            for (var j = 0; j < dictValueArr.length; j++) {
                if (dictValueArr[j] == dictData[i].dict_value) {
                    var cssStyle = dictData[i].css_style;
                    str.push('<span style="' + cssStyle + '" val="' + dictValue + '">' + dictData[i].dict_label + '</span>');
                    break;
                }
            }
        }
        str.join(",");
    } else {
        var str = "";
        for (var i = 0; i < dictData.length; i++) {
            if (dictValue == dictData[i].dict_value) {
                var cssStyle = dictData[i].css_style;
                str = '<span style="' + cssStyle + '" val="' + dictValue + '">' + dictData[i].dict_label + '</span>';
                break;
            }
        }
    }
    if (str == "" && customStr) {
        return customStr;
    }
    return str;
}

function clickCheckRow() {
    //单击行勾选checkbox事件
    layui.$(document).on("click", ".layui-table-body table.layui-table tbody tr", function() {
        var index = $(this).attr('data-index');
        var tableBox = $(this).parents('.layui-table-box');
        //存在固定列
        if (tableBox.find(".layui-table-fixed.layui-table-fixed-l").length > 0) {
            tableDiv = tableBox.find(".layui-table-fixed.layui-table-fixed-l");
        } else {
            tableDiv = tableBox.find(".layui-table-body.layui-table-main");
        }
        var checkCell = tableDiv.find("tr[data-index=" + index + "]").find("td div.laytable-cell-checkbox div.layui-form-checkbox I");
        if (checkCell.length > 0) {
            checkCell.click();
        }
    });
    layui.$(document).on("click", "td div.laytable-cell-checkbox div.layui-form-checkbox", function(e) {
        e.stopPropagation();
    });
    //单击行勾选radio事件
    layui.$(document).on("click", ".layui-table-body table.layui-table tbody tr", function() {
        var index = $(this).attr('data-index');
        var tableBox = $(this).parents('.layui-table-box');
        //存在固定列
        if (tableBox.find(".layui-table-fixed.layui-table-fixed-l").length > 0) {
            tableDiv = tableBox.find(".layui-table-fixed.layui-table-fixed-l");
        } else {
            tableDiv = tableBox.find(".layui-table-body.layui-table-main");
        }
        var checkCell = tableDiv.find("tr[data-index=" + index + "]").find("td div.laytable-cell-radio div.layui-form-radio I");
        if (checkCell.length > 0) {
            checkCell.click();
        }
    });
    layui.$(document).on("click", "td div.laytable-cell-radio div.layui-form-radio", function(e) {
        e.stopPropagation();
    });
}

function whatBrowser() {
    var body = document.getElementsByTagName("body")[0];
    if (typeof body.style.WebkitAnimation != "undefined") {
        return true;
    } else {
        return false;
    }
}

function openFrame(title, url, area = ['100%', '100%'], shade = 0.3, skin = '') {
    if (isMobile()) {
        area = ['100%', '100%'];
    }
    if (area[0] == '100%' && area[1] == '100%') {
        shade = false;
    }
    var layerIndex = layui.layer.open({
        type: 2,
        area: area,
        title: title,
        fixed: true,
        shade: shade,
        skin: skin, //layui-layer-lan //layui-layer-molv
        maxmin: true,
        min: function name(layero) {
            $("#layui-layer-shade" + layerIndex).hide();
        },
        max: function name(layero) {
            $("#layui-layer-shade" + layerIndex).show();
        },
        restore: function name(layero) {
            $("#layui-layer-shade" + layerIndex).show();
        },
        content: url
    });
}
//ajax post请求
function request(url, data, callback) {
    // loadingIndex = layer.load(2);
    var accesstoken = localStorage.getItem("accesstoken");
    var accessuid = localStorage.getItem("accessuid");
    layui.jquery.ajax({
        url: url,
        type: "post",
        headers: {
            'accessuid': accessuid,
            'accesstoken': accesstoken,
        },
        async: true,
        contentType: "application/json;charset=utf-8",
        dataType: 'json',
        data: JSON.stringify(data),
        beforeSend: function() {},
        complete: function() {},
        success: function(ret) {
            if (ret.code == 401) {
                localStorage.setItem("accesstoken", "");
                localStorage.setItem("accessuid", "");
                layer.alert(ret.msg, {
                    icon: 1,
                    closeBtn: 0
                }, function(index) {
                    //关闭弹窗
                    layer.close(index);
                    window.location.href = project_path + "login.html";
                });
            } else if (ret.code == 403) {
                layer.msg(ret.msg, {
                    icon: 5
                });
            } else {
                callback(ret);
            }
        }
    });
}

function type(val) {
    var type = Object.prototype.toString.call(val);
    var reg = /^\[[a-zA-Z]+\s+([a-zA-Z]+)\]$/;
    if (reg.test(type)) {
        return RegExp.$1.toLowerCase();
    }
    return '';
}

function trim(str) {
    if (type(str) === 'string') {
        return str.replace(/^\s+|\s+$/, '');
    } else {
        return str;
    }
}

function getQueryString(item) {
    var url = decodeURI(decodeURI(location.search)); //获取url中"?"符后的字串，使用了两次decodeRUI解码
    var theRequest = new Object();
    if (url.indexOf("?") != -1) {
        var str = url.substr(1);
        strs = str.split("&");
        for (var i = 0; i < strs.length; i++) {
            strs[i] = strs[i].replace(/=/, '&');
            var itemArr = strs[i].split("&");
            theRequest[itemArr[0]] = unescape(itemArr[1]);
        }
        return trim(theRequest[item]);
    }
}

function isEmpty(value) {
    if (typeof(value) === 'number') {
        if (value === 0) {
            return true;
        } else {
            return false;
        }
    } else if (typeof(value) === 'boolean') {
        if (value === false) {
            return true;
        } else {
            return false;
        }
    } else if (Object.prototype.toString.call(value) === '[object Array]') {
        if (value.length === 0) {
            return true;
        } else {
            return false;
        }
    } else if (Object.prototype.toString.call(value) === '[object Object]') {
        if (JSON.stringify(value) === '{}') {
            return true;
        } else {
            return false;
        }
    } else if (typeof(value) === 'string') {
        value = value.replace(/(^\s*)|(\s*$)/g, "");
    }
    if (value === undefined || value === 'undefined' || value === null || value === 'null' || typeof(value) === 'undefined' || value === 'NULL' || value === "" || value === 'false' || value === '0' || value === '[]' || value === '{}') {
        return true;
    } else {
        return false;
    }
}

function getFormData($form) {
    var unindexed_array = $form.serializeArray();
    var indexed_array = {};
    $.map(unindexed_array, function(n, i) {
        indexed_array[n['name']] = n['value'];
    });
    return indexed_array;
}

function formToJson(data) {
    data = data.replace(/&/g, "\",\"");
    data = data.replace(/=/g, "\":\"");
    data = "{\"" + data + "\"}";
    data = decodeURIComponent(data);
    data = eval('(' + data + ')');
    return data;
}
//数据排序
function dataSort() {
    layui.table.on('sort(data-list)', function(obj) {
        var formData = $("form").serialize();
        var searchFormJson = {};
        if (!isEmpty(formData)) {
            searchFormJson = formToJson($("form").serialize());
        }
        searchFormJson.lup_sort_field = obj.field;
        searchFormJson.lup_sort_order = obj.type;
        layui.table.reload('data-list', {
            initSort: obj,
            where: searchFormJson
        });
    });
}
//统一加载数据方法
function loadData(url, cols, toolbar, callback, height = "full-110", page = { groups: 5 }, limit = 20, defaultToolbar = ['filter', 'print']) {
    if (!toolbar) {
        toolbar = false;
    }
    if (toolbar == '<div class="layui-btn-container"></div>') {
        toolbar = false;
    }
    if (height == "full-110") {
        var searchBoxHeight = $(".search-box").height();
        searchBoxHeight = parseFloat(searchBoxHeight);
        height = $(window).height() - 22 - searchBoxHeight;
        if (height <= 400) {
            height = 400;
        }
    }
    if (isMobile()) {
        height = "";
    }
    var accesstoken = localStorage.getItem("accesstoken");
    var accessuid = localStorage.getItem("accessuid");
    layui.table.render({
        elem: '#data-list',
        url: url,
        method: 'post',
        contentType: 'application/json',
        headers: {
            'accessuid': accessuid,
            'accesstoken': accesstoken
        },
        toolbar: toolbar,
        cellMinWidth: 80,
        loading: false,
        even: true,
        height: height,
        autoSort: false,
        defaultToolbar: defaultToolbar,
        cols: [cols],
        done: function(res, curr, count) {
            var code = res.code;
            if (code != 200) {
                layer.msg(res.msg);
                return false;
            }
            layui.jquery(".layui-table-tool").css("background", "#f8f8f8");
        },
        error: function(obj, content) {},
        // skin:'row',
        // size: 'sm',
        page: page,
        limit: limit,
        limits: [20, 30, 50, 80, 100, 200, 500, 1000],
        response: {
            statusCode: 200 //重新规定成功的状态码为 200，table 组件默认为 0
        },
        parseData: function(res) { //将原始数据解析成 table 组件所规定的数据
            if (callback) {
                callback(res);
            }
            if (res.code == 401) {
                localStorage.setItem("accesstoken", null);
                localStorage.setItem("accessuid", null);
                layer.alert(res.msg, {
                    icon: 1,
                    closeBtn: 0
                }, function(index) {
                    //关闭弹窗
                    layer.close(index);
                    window.location.href = project_path + "login.html";
                });
            } else if (res.code == 403) {
                layer.msg(res.msg);
                return false;
            } else {
                return {
                    "code": res.code, //解析接口状态
                    "msg": res.msg, //解析提示文本
                    "count": res.data.total || res.data.length || 0, //解析数据长度
                    "data": res.data.rows || res.data || [] //解析数据列表
                };
            }

        }
    });
    dataSort();
}
//统一提交方法
function frameSubmit(url, isReloadTableList = true, callback = false, dataJson = false, dataConstructor = false) {
    var index = parent.layer.getFrameIndex(window.name);
    form.verify({
        otherReq: function(value, item) {
            var $ = layui.$;
            var verifyName = $(item).attr('name'),
                verifyType = $(item).attr('type'),
                formElem = $(item).parents('.layui-form'), //获取当前所在的form元素，如果存在的话
                layReqtext = $(item).attr("lay-reqtext") || "必填项不能为空",
                verifyElem = formElem.find('input[name=' + verifyName + ']'), //获取需要校验的元素
                isTrue = verifyElem.is(':checked'), //是否命中校验
                focusElem = verifyElem.next().find('i.layui-icon'); //焦点元素
            //alert(verifyName);
            if (!isTrue || !value) {
                //定位焦点
                focusElem.css(verifyType == 'radio' ? { "color": "#FF5722" } : { "border-color": "#FF5722" });
                //对非输入框设置焦点
                focusElem.first().attr("tabIndex", "1").css("outline", "0").blur(function() {
                    focusElem.css(verifyType == 'radio' ? { "color": "" } : { "border-color": "" });
                }).focus();
                return layReqtext;
            }
        }
    });
    //监听提交
    layui.form.on('submit(form-submit)', function(data) {
        var isReturn = true;
        var returnMsg = "";
        layui.jquery(".data-check-type-tel").each(function(index, obj) {
            var val = $(obj).val();
            if (val != '') {
                var myreg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
                if (!myreg.test(val)) {
                    isReturn = false;
                    returnMsg = "手机号码格式不正确";
                    layui.jquery(obj).focus();
                    layui.jquery(obj).addClass("layui-form-danger");
                    layui.layer.tips(returnMsg, obj, {
                        tips: [1, '#4d4d4d'],
                        time: 4000
                    });
                    return false;
                }
            }
        });
        if (isReturn == false) {
            return false;
        }
        layui.jquery(".data-check-type-email").each(function(index, obj) {
            var val = $(obj).val();
            if (val != '') {
                var myreg = /^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/;
                if (!myreg.test(val)) {
                    isReturn = false;
                    returnMsg = "邮箱格式不正确";
                    layui.jquery(obj).focus();
                    layui.jquery(obj).addClass("layui-form-danger");
                    layui.layer.tips(returnMsg, obj, {
                        tips: [1, '#4d4d4d'],
                        time: 4000
                    });
                    return false;
                }
            }
        });
        if (isReturn == false) {
            return false;
        }
        layui.jquery(".data-check-type-http").each(function(index, obj) {
            var val = $(obj).val();
            if (val != '') { 
                var myreg = /^([hH][tT]{2}[pP]:\/\/|[hH][tT]{2}[pP][sS]:\/\/)(([A-Za-z0-9-~]+)\.)+([A-Za-z0-9-~\/])+$/;
                if (!myreg.test(val)) {
                    isReturn = false;
                    returnMsg = "网址格式不正确";
                    layui.jquery(obj).focus();
                    layui.jquery(obj).addClass("layui-form-danger");
                    layui.layer.tips(returnMsg, obj, {
                        tips: [1, '#4d4d4d'],
                        time: 4000
                    });
                    return false;
                }
            }
        });
        if (isReturn == false) {
            return false;
        }
        layui.jquery(".data-check-type-int").each(function(index, obj) {
            var val = $(obj).val();
            if (val != '') { 
                var regPos = /^\d+$/; // 非负整数 
                var regNeg = /^\-[1-9][0-9]*$/; // 负整数
                if (!regPos.test(val)) {
                    isReturn = false;
                    returnMsg = "不是有效的整数";
                    layui.jquery(obj).focus();
                    layui.jquery(obj).addClass("layui-form-danger");
                    layui.layer.tips(returnMsg, obj, {
                        tips: [1, '#4d4d4d'],
                        time: 4000
                    });
                    return false;
                }
            }
        });
        if (isReturn == false) {
            return false;
        }
        layui.jquery(".data-check-type-float").each(function(index, obj) {
            var val = $(obj).val();
            if (val != '') { 
                var regPos = /^\d+(\.\d+)?$/; //非负浮点数
                var regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数
                if (!regPos.test(val) && !regNeg.test(val)) {
                    isReturn = false;
                    returnMsg = "不是有效的数字";
                    layui.jquery(obj).focus();
                    layui.jquery(obj).addClass("layui-form-danger");
                    layui.layer.tips(returnMsg, obj, {
                        tips: [1, '#4d4d4d'],
                        time: 4000
                    });
                    return false;
                }
            }
        });
        if (isReturn == false) {
            return false;
        }

        layui.jquery(".data-check-type-money").each(function(index, obj) {
            var val = $(obj).val();
            if (val != '') { 
                var regPos = /^\d+(\.\d+)?$/; //非负浮点数
                var regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数
                if (!regPos.test(val) && !regNeg.test(val)) {
                    isReturn = false;
                    returnMsg = "不是有效的金额";
                    layui.jquery(obj).focus();
                    layui.jquery(obj).addClass("layui-form-danger");
                    layui.layer.tips(returnMsg, obj, {
                        tips: [1, '#4d4d4d'],
                        time: 4000
                    });
                    return false;
                }
            }
        });
        if (isReturn == false) {
            return false;
        }
        layui.jquery(".data-check-type-money").each(function(index, obj) {
            var val = $(obj).val();
            if (val != '') { 
                var regPos = /^\d+(\.\d+)?$/; //非负浮点数
                var regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数
                if (!regPos.test(val) && !regNeg.test(val)) {
                    isReturn = false;
                    returnMsg = "不是有效的金额";
                    layui.jquery(obj).focus();
                    layui.jquery(obj).addClass("layui-form-danger");
                    layui.layer.tips(returnMsg, obj, {
                        tips: [1, '#4d4d4d'],
                        time: 4000
                    });
                    return false;
                }
            }
        });
        if (isReturn == false) {
            return false;
        }
        layui.jquery(".data-check-type-idCard").each(function(index, obj) {
            var val = $(obj).val();
            if (val != '') { 
                if (!isIdentityCodeValid(val)) {
                    isReturn = false;
                    returnMsg = "身份证号码不正确";
                    layui.jquery(obj).focus();
                    layui.jquery(obj).addClass("layui-form-danger");
                    layui.layer.tips(returnMsg, obj, {
                        tips: [1, '#4d4d4d'],
                        time: 4000
                    });
                    return false;
                }
            }
        });
        if (isReturn == false) {
            return false;
        }


        var btn = layui.jquery(this);
        if (btn.hasClass("layui-btn-disabled")) {

            return false;
        }
        // return false;
        btn.addClass('layui-btn-disabled');
        var loading = layer.load(2, {
            shade: [0.1, '#393D49'],
        });
        layer.msg('正在提交数据...', {
            shade: [0.1, '#393D49'],
            time: 2000
        });
        if (dataJson) {
            var requestData = dataJson;
        } else {
            var requestData = data.field;
        }
        //field-type-bigint
        $(".data-check-type-timeMs").each(function(index, obj) {
            var name = $(obj).attr("name") || "";
            if (name) {
                requestData[name] = dateToTimestamp(requestData[name], 'timeMs');
            }
        });
        $(".data-check-type-time").each(function(index, obj) {
            var name = $(obj).attr("name") || "";
            if (name) {
                requestData[name] = dateToTimestamp(requestData[name], 'time');
            }
        });
        $(".field-type-bigint").each(function(index, obj) {
            var name = $(obj).attr("name") || "";
            if (name && requestData[name] == "") {
                requestData[name] = 0;
            }
        });
        $(".field-type-int").each(function(index, obj) {
            var name = $(obj).attr("name") || "";
            if (name && requestData[name] == "") {
                requestData[name] = 0;
            }
        });
        $(".field-type-tinyint").each(function(index, obj) {
            var name = $(obj).attr("name") || "";
            if (name && requestData[name] == "") {
                requestData[name] = 0;
            }
        });
        $(".field-type-decimal").each(function(index, obj) {
            var name = $(obj).attr("name") || "";
            if (name && requestData[name] == "") {
                requestData[name] = 0.00;
            }
        });

        if (dataConstructor) {
            dataConstructor(data.field, this);
        }
        request(url, data.field, function(ret) {
            var code = ret.code;
            // layer.close(loading);
            layer.closeAll('loading');
            setTimeout(function() {
                btn.removeClass('layui-btn-disabled');
            }, 1500);
            if (code == 200) {
                setTimeout(function() {
                    parent.layer.close(index);
                }, 1500);
                if (callback) {
                    callback(ret);
                }
                if (isReloadTableList) {
                    parent.layui.table.reload('data-list');
                }
                layer.msg(ret.msg, {
                    shade: [0.1, '#393D49'],
                    time: 2000,
                    icon: 6
                });

            } else {
                layer.msg(ret.msg, {
                    shade: [0.1, '#393D49'],
                    time: 2000,
                    icon: 5
                });
            }
        });
        return false;
    });
}
//td双击编辑
function tableEdit(tableName) {
    layui.table.on('edit(data-list)', function(obj) {
        var value = obj.value; //得到修改后的值
        var data = obj.data //得到所在行所有键值
        var fieldName = obj.field; //得到字段
        var that = this;
        var oldText = layui.jquery(that).prev().text();
        // console.log(oldText);
        var url = base_gateway + 'sys/ajax/tableEdit';
        //console.log({ "table_name": tableName, "id": data.id, "field_name": fieldName, "value": value });
        request(url, { "table_name": tableName, "id": data.id, "field_name": fieldName, "value": value }, function(ret) {
            var code = ret.code;
            if (code == 200) {
                layer.msg(ret.msg, {
                    icon: 6
                });
            } else {
                var oldData = JSON.parse('{"' + fieldName + '":"' + oldText + '"}');
                //重新赋值
                obj.update(oldData);
                layer.msg(ret.msg, {
                    icon: 5
                });
            }
        });

    });
}
//初始化表格顶部操作按钮
function pageInit(callback) {
    var code = getQueryString("code");
    if (isEmpty(code)) {
        return false;
    }
    //查询按钮
    var url = base_gateway + 'sys/init/getPageAction/' + code;
    request(url, { page: 1, limit: 10000 }, function(ret) {
        var code = ret.code;
        if (code == 200) {
            //设置按钮
            var actionList = ret.data.action;
            var toolbarHtml = '<div class="layui-btn-container">';
            for (var i = 0; i < actionList.length; i++) {
                var _jump = actionList[i].jump;
                var _gateway = actionList[i].api_url;
                var _query = actionList[i].query_url;
                var _bgColor = actionList[i].bg_color;
                var _actionName = actionList[i].action_name;
                var _bindEvent = actionList[i].bind_event;
                var _tips = actionList[i].tips;
                var _width = actionList[i].width;
                var _height = actionList[i].height;
                var pars = { jump: _jump, gateway: _gateway, query: _query, tips: _tips, width: _width, height: _height };
                pars = encodeURIComponent(JSON.stringify(pars));
                toolbarHtml += '<button class="layui-btn layui-btn-sm" style="background-color:' + _bgColor + '" pars="' + pars + '" lay-event="' + _bindEvent + '"> ' + _actionName + ' </button>';
            }
            toolbarHtml += '</div>';
            if (callback) {
                callback(ret.data.page, toolbarHtml);
            }
        } else if (ret.code == 403) {
            layer.msg(ret.msg, {
                icon: 5
            });
        } else {
            layer.msg(ret.msg, {
                icon: 5
            });
        }
    });
}

//监听搜索
function doSearch(callback) {
    layui.form.on('submit(data-search-btn)', function(data) {
        //执行搜索重载
        layui.table.reload('data-list', {
            page: {
                curr: 1
            },
            where: data.field
        });
        if (callback) {

            callback(data.field);
        }
        return false;
    });
}
/**
 * toolbar监听事件
 */
function toolbarTap(callback, callbackRet) {

    table.on('toolbar(data-list)', function(obj) {
        var pars = layui.jquery(this).attr("pars");
        pars = decodeURIComponent(pars);
        pars = eval('(' + pars + ')');
        var jump = pars.jump;
        var gateway = pars.gateway;
        var query = pars.query;
        // console.log(query);
        var tips = pars.tips;
        var width = pars.width;
        var height = pars.height;
        var area = [width, height];

        if (isEmpty(tips)) {
            tips = "<font style='color:red'>参数未定义</font>";
        }
        if (isEmpty(width)) {
            width = "100%";
        }
        if (isEmpty(height)) {
            height = "100%";
        }
        var checkStatus = table.checkStatus(obj.config.id);
        if (callback) {
            callback(checkStatus.data, pars, obj.event);
        }
        if (obj.event === 'add') { // 监听添加操作
            openFrame(tips, jump + "?gateway=" + gateway + "&version=" + static_version, area);
        } else if (obj.event === 'del') {
            if (checkStatus.data.length == 0) {
                layer.msg('请至少选择一记录');
            } else {
                if (checkStatus.data.length == 1) {
                    tips = '您选择了<span style="color:green;font-size:28px;">【' + checkStatus.data.length + '】</span>条数据，确定要删除吗？';
                } else {
                    tips = '您选择了<span style="color:red;font-size:28px;">【' + checkStatus.data.length + '】</span>条数据，确定要删除吗？';
                }
                var ids = "";
                for (var i = 0; i < checkStatus.data.length; i++) {
                    ids += checkStatus.data[i].id + ",";
                    // ids[i] = checkStatus.data[i].id;
                }
                ids = ids.substring(0, ids.length - 1);
                layer.confirm(tips, {
                    title: '温馨提示',
                    btn: ['确定', '取消'],
                    icon: 5
                }, function(index) {
                    var data = checkStatus.data;
                    var url = base_gateway + gateway;
                    request(url, { ids: ids }, function(ret) {

                        if (callbackRet) {
                            callbackRet(checkStatus.data, ret, obj.event);
                        }
                        var code = ret.code;
                        if (code == 200) {
                            layer.msg(ret.msg, {
                                icon: 6
                            });
                            table.reload('data-list');
                        } else {
                            layer.msg(ret.msg, {
                                icon: 5
                            });
                        }
                    });
                });
            }
        } else if (obj.event === 'edit') { // 监听添加操作
            if (checkStatus.data.length == 0) {
                layer.msg('请选择一条记录');
            } else if (checkStatus.data.length > 1) {
                layer.msg('只能勾选一条记录');
            } else if (checkStatus.data.length == 1) {
                var data = checkStatus.data;
                openFrame(tips, jump + '?id=' + data[0].id + "&gateway=" + gateway + "&query=" + query + "&version=" + static_version, area);
            }
        }
    });
}

function isMobile() {
    var info = navigator.userAgent;
    var agents = ["Android", "iPhone", "SymbianOS", "Windows Phone", "iPod", "iPad"];
    for (var i = 0; i < agents.length; i++) {
        if (info.indexOf(agents[i]) >= 0) return true;
    }
    return false;
}

//时间戳转换日期
function timeStampFmt(date) {
    if (date == "" || date == 0) {
        return "";
    }
    var ms = "";
    date = "" + date + "";
    var _date;
    if (date.length == 10) {
        _date = new Date(parseInt(date) * 1000);
    } else if (date.length == 13) {
        ms = date.substring(date.length - 3);
        _date = new Date(parseInt(date));
    }
    var y = _date.getFullYear();
    var m = _date.getMonth() + 1;
    m = m < 10 ? ('0' + m) : m;
    var d = _date.getDate();
    d = d < 10 ? ('0' + d) : d;
    var h = _date.getHours();
    h = h < 10 ? ('0' + h) : h;
    var minute = _date.getMinutes();
    var second = _date.getSeconds();
    minute = minute < 10 ? ('0' + minute) : minute;
    second = second < 10 ? ('0' + second) : second;
    // console.log( y + '-' + m + '-' + d + ' ' + '　' + h + ':' + minute + ':' + second)
    var dates = y + '-' + m + '-' + d + " " + h + ":" + "" + minute + ":" + second;
    if (ms != "") {
        return dates + "." + ms;
    } else {
        return dates;
    }
}
//初始化富文本编辑器
function editor(el) {
    const E = window.wangEditor;
    const editor = new E("#" + el);
    editor.config.height = 500;
    //该方式性能比较低，所有使用上传接口
    // editor.config.uploadImgShowBase64 = true;
    //图片上传配置
    editor.config.uploadImgServer = base_gateway + 'sys/upload/uploadFile';
    //图片最大 10M
    editor.config.uploadImgMaxSize = 10 * 1024 * 1024;
    editor.config.uploadImgAccept = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'];
    // 一次最多上传 5 个图片
    editor.config.uploadImgMaxLength = 20;

    //自定义 fileName
    editor.config.uploadFileName = 'file';

    // editor.config.uploadImgParams = {
    //     token: 'xxxxx',
    //     x: 100
    // };
    editor.config.uploadImgHeaders = {
        accessuid: localStorage.getItem("accessuid"),
        accesstoken: localStorage.getItem("accesstoken"),
    }

    editor.config.uploadImgHooks = {
        // 上传图片之前
        before: function(xhr) {
            // console.log(xhr)
            // 可阻止图片上传
            // return {
            //     prevent: true,
            //     msg: '需要提示给用户的错误信息'
            // }
        },
        // 图片上传并返回了结果，图片插入已成功
        success: function(xhr) {
            console.log('success', xhr)
        },
        // 图片上传并返回了结果，但图片插入时出错了
        fail: function(xhr, editor, resData) {
            console.log('fail', resData)
        },
        // 上传图片出错，一般为 http 请求的错误
        error: function(xhr, editor, resData) {
            // console.log('error', xhr, resData)
            layer.msg("请求错误");
        },
        // 上传图片超时
        timeout: function(xhr) {
            layer.msg("请求超时");
            //console.log('timeout')
        },
        // 图片上传并返回了结果，想要自己把图片插入到编辑器中
        // 例如服务器端返回的不是 { errno: 0, data: [...] } 这种格式，可使用 customInsert
        customInsert: function(insertImgFn, result) {
            // result 即服务端返回的接口
            if (result.code == 200) {
                layer.msg(result.msg);
                // insertImgFn 可把图片插入到编辑器，传入图片 src ，执行函数即可
                insertImgFn(result.data.file_url)
            } else {
                layer.msg(result.msg);
            }
        }
    }

    //视频上传配置
    editor.config.uploadVideoServer = base_gateway + 'sys/upload/uploadFile';
    // 1024m
    editor.config.uploadVideoMaxSize = 1 * 1024 * 1024 * 1024;
    //timeout 即上传接口等待的最大时间，默认是 5分钟，可以自己修改。
    editor.config.uploadVideoTimeout = 1000 * 60 * 5;
    editor.config.uploadVideoName = 'file';

    editor.config.uploadVideoHeaders = {
        accessuid: localStorage.getItem("accessuid"),
        accesstoken: localStorage.getItem("accesstoken"),
    }
    editor.config.uploadVideoHooks = {
        // 上传视频之前
        before: function(xhr) {

        },
        // 视频上传并返回了结果，视频插入已成功
        success: function(xhr) {},
        // 视频上传并返回了结果，但视频插入时出错了
        fail: function(xhr, editor, resData) {
            console.log('fail', resData)
        },
        // 上传视频出错，一般为 http 请求的错误
        error: function(xhr, editor, resData) {
            layer.msg("请求错误");
            // console.log('error', xhr, resData)
        },
        // 上传视频超时
        timeout: function(xhr) {
            layer.msg("请求超时");
        },
        // 视频上传并返回了结果，想要自己把视频插入到编辑器中
        // 例如服务器端返回的不是 { errno: 0, data: { url : '.....'} } 这种格式，可使用 customInsert
        customInsert: function(insertVideoFn, result) {
            // result 即服务端返回的接口
            console.log('customInsert', result)
            if (result.code == 200) {
                layer.msg(result.msg);
                // insertVideoFn 可把视频插入到编辑器，传入视频 src ，执行函数即可
                insertVideoFn(result.data.file_url)
            } else {
                layer.msg(result.msg);
            }
        }
    }
    editor.config.menus = [
        'head',
        'bold',
        'fontSize',
        'fontName',
        'italic',
        'underline',
        'strikeThrough',
        'indent',
        'lineHeight',
        'foreColor',
        'backColor',
        'link',
        'list',
        'justify',
        'quote',
        'emoticon',
        'image',
        'video',
        'table',
        'code',
        'splitLine',
        'undo',
        'redo',
    ];

    editor.config.onchange = function(newHtml) {
        // try {
        //     if (typeof(eval(filterXSS)) == "function") {
        //         // newHtml = filterXSS(newHtml);
        //     } else {
        //         console.log("未引入xss.min.js！");
        //     }
        // } catch (e) {
        //     console.log("未引入xss.min.js");
        // }

        $("textarea[name='" + el + "']").val(newHtml);
    };
    editor.create();
    return editor;
}
//初始化日历插件
function initCalendar() {
    $(".date").each(function(index, obj) {
        var range = $(obj).attr("range") || "";
        var name = $(obj).attr("name");
        var defaultDate = $(obj).attr("default-date") || "";
        var spStartEnd = $(obj).attr("sp-start-end") || "";
        var dataCheckType = $(obj).attr("data-check-type");
        if (defaultDate == 'now' && range == '') {
            defaultDate = new Date();
        } else {
            defaultDate = "";
        }
        if (range != "") {
            $(obj).css("width", "165px");
        }
        layui.laydate.render({
            elem: obj,
            trigger: 'click',
            type: 'date',
            value: defaultDate,
            range: range,
            done: function(value, date, endDate) {
                var objStart = $("input[name='" + name + "_between_start']");
                var objEnd = $("input[name='" + name + "_between_end']");
                if (value.length == 0 || value == "") {
                    if (objStart) {
                        objStart.val("");
                    }
                    if (objEnd) {
                        objEnd.val("");
                    }
                    return false;
                }
                if (range == "~") {
                    var dateArr = value.split("~");
                    var spStart = "";
                    var spEnd = "";
                    if (spStartEnd != "") {
                        var spStartEndArr = spStartEnd.split("~");
                        spStart = " " + trim(spStartEndArr[0]);
                        spEnd = " " + trim(spStartEndArr[1]);
                    }

                    if (objStart) {
                        var start = trim(dateArr[0]) + "" + spStart;
                        start = dateToTimestamp(start, dataCheckType);
                        objStart.val(start);
                    }
                    if (objEnd) {
                        var end = trim(dateArr[1]) + "" + spEnd;
                        end = dateToTimestamp(end, dataCheckType);
                        objEnd.val(end);
                    }
                }
            }
        });
    });
    $(".datetime").each(function(index, obj) {
        var range = $(obj).attr("range") || "";
        var name = $(obj).attr("name");
        var defaultDate = $(obj).attr("default-date") || "";

        var spStartEnd = $(obj).attr("sp-start-end") || "";
        var dataCheckType = $(obj).attr("data-check-type") || "";
        var val = $(obj).val();

        if(val!="") {
            if ($(obj).hasClass("data-check-type-timeMs")){
                defaultDate = timeStampFmt(val/1000);
            }
            if ($(obj).hasClass("data-check-type-time")){
                defaultDate = timeStampFmt(val);
            }
            if ($(obj).hasClass("data-check-type-ymdhis")){
                defaultDate = val;
            }
        }else {
            if (defaultDate == 'now' && range == '') {
                defaultDate = new Date();
            } else {
                defaultDate = "";
            }
        }

        if(defaultDate=='now'){
            defaultDate = "";
        }
        $(obj).val(defaultDate);


        if (range != "") {
            $(obj).css("width", "275px");
        }
        layui.laydate.render({
            elem: obj,
            trigger: 'click',
            type: 'datetime',
            value: defaultDate,
            range: range,
            done: function(value, date, endDate) {
                var objStart = $("input[name='" + name + "_between_start']");
                var objEnd = $("input[name='" + name + "_between_end']");
                if (value.length == 0 || value == "") {
                    if (objStart) {
                        objStart.val("");
                    }
                    if (objEnd) {
                        objEnd.val("");
                    }
                    return false;
                }
                if (range == "~") {
                    var dateArr = value.split("~");
                    var spStart = 0;
                    var spEnd = 0;
                    if (spStartEnd != "") {
                        var spStartEndArr = spStartEnd.split("~");
                        spStart = trim(spStartEndArr[0]);
                        spEnd = trim(spStartEndArr[1]);
                    }

                    if (objStart) {
                        var start = trim(dateArr[0]);
                        start = dateToTimestamp(start, dataCheckType);
                        if (dataCheckType == 'time' || dataCheckType == 'timeMs') {
                            objStart.val(parseInt(start) + parseInt(spStart));
                        } else {
                            objStart.val(start);
                        }
                    }
                    if (objEnd) {
                        var end = trim(dateArr[1]);
                        end = dateToTimestamp(end, dataCheckType);
                        if (dataCheckType == 'time' || dataCheckType == 'timeMs') {
                            objEnd.val(parseInt(end) + parseInt(spEnd));
                        } else {
                            objEnd.val(end);
                        }
                    }
                }
            }
        });
    });
}

function addUploadBox(html, id) {
    html = decodeURIComponent(html);
    var total = $("#" + id + "_total").val() || 1;
    var nextNum = parseInt(total) + 1;
    html = html.replace(/current_num/g, "" + nextNum + "");
    $("#" + id + "_box").append(html);
    $("#" + id + "_total").val(nextNum);
    multiFileRemarksListen();
    $('.multiFile_' + id + '').blur(function() {
        // $("input[name='country']").val();
        var valArr = [];
        $(".multiFile_" + id).each(function(index, obj) {
            var val = $(this).val();
            valArr.push(val);
        });
        $("input[name='" + id + "']").val(valArr);
    });
}

function delUploadBox(obj, name) {
    var id = $(obj).parent().attr("id");
    layer.confirm("确定要删除该上传框吗？", function(index) {
        $("#" + id).remove();
        var total = $("#" + name + "_total").val() || 1;
        var nextNum = parseInt(total) - 1;
        $("#" + name + "_total").val(nextNum);

        var valArr = [];
        $(".multiFile_" + name).each(function(index, obj) {
            var val = $(this).val();
            valArr.push(val);
        });
        $("input[name='" + name + "']").val(valArr);



        var arr = [];
        //遍历所有的附件框
        for (var i = 1; i <= total; i++) {
            var file = $("input[name='" + name + "_" + i + "_file']").val() || "";
            var remarks = $("input[name='" + name + "_" + i + "_remarks']").val() || "";
            if (remarks != "" || file != "") {
                var json = { url: file, remarks: remarks };
                arr.push(json);
            }
        }
        if (arr.length > 0) {
            $("textarea[name='" + name + "']").val(JSON.stringify(arr));
        } else {
            $("textarea[name='" + name + "']").val("");
        }

        layer.msg("已删除");
    });

}

function openUploadFileBox(obj, fieldName) {
    var name = $(obj).attr("name");
    var exts = $(obj).attr("exts") || "";
    var path = $(obj).attr("path") || "";
    var thumb = $(obj).attr("thumb") || "";
    var remarks = $(obj).attr("remarks") || "后台上传";
    layui.layer.open({
        type: 2,
        area: ['300px', '200px'],
        title: '上传文件',
        fixed: true,
        shade: 0.3,
        skin: 'layui-layer-molv', //layui-layer-lan //layui-layer-molv
        maxmin: false,
        content: project_path + "common/upload.html?name=" + name + "&field_name=" + fieldName + "&exts=" + exts + "&path=" + path + "&thumb=" + thumb + "&remarks=" + remarks
    });
}


function multiFileRemarksListen() {
    layui.$(".multiFileRemarks_remarks").on("input propertychange", function() {
        var arr = [];
        var oriName = $(this).attr("ori-name");
        var total = $("#" + oriName + "_total").val();
        //遍历所有的附件框
        for (var i = 1; i <= total; i++) {
            var file = $("input[name='" + oriName + "_" + i + "_file']").val() || "";
            var remarks = $("input[name='" + oriName + "_" + i + "_remarks']").val() || "";
            if (remarks != "" || file != "") {
                var json = { url: file, remarks: remarks };
                arr.push(json);
            }
        }
        if (arr.length > 0) {
            $("textarea[name='" + oriName + "']").val(JSON.stringify(arr));

        } else {
            $("textarea[name='" + oriName + "']").val("");
        }
    });

    layui.$(".multiFileRemarks_file").on("input propertychange", function() {
        var arr = [];
        var oriName = $(this).attr("ori-name");
        var total = $("#" + oriName + "_total").val();
        //遍历所有的附件框
        for (var i = 1; i <= total; i++) {
            var file = $("input[name='" + oriName + "_" + i + "_file']").val() || "";
            var remarks = $("input[name='" + oriName + "_" + i + "_remarks']").val() || "";
            if (remarks != "" || file != "") {
                var json = { url: file, remarks: remarks };
                arr.push(json);
            }
        }
        if (arr.length > 0) {
            $("textarea[name='" + oriName + "']").val(JSON.stringify(arr));

        } else {
            $("textarea[name='" + oriName + "']").val("");
        }
    });

}

function initUploadFile() {

    //遍历所有多附件上传信息
    $(".multiFile").each(function(index, obj) {
        var thumb = $(this).attr("thumb") || "";
        var path = $(this).attr("path") || "";
        var exts = $(this).attr("exts") || "";
        var name = $(this).attr("name") || "";
        var layVerify = $(this).attr("lup-lay-verify") || "";
        var layReqtext = $(this).attr("lay-reqtext") || "";
        var placeholder = $(this).attr("placeholder") || "请上传...";
        var value = $(this).attr("value") || "";

        var addHtml = '<div style="display: -webkit-flex;display: flex;margin-top:10px;position: relative;" id="' + name + '_box_current_num">';
        addHtml += '<div onclick=delUploadBox(this,"' + name + '") style="display: -webkit-flex;display: flex;width:auto;line-height:38px;padding-right:10px;"><button type="button" style="height:38px;width:38px;padding:0px;text-align:center" class="layui-btn layui-btn-danger">-</button></div>';
        addHtml += '<div style="display: -webkit-flex;display: flex;flex:1;"><input onclick=openUploadFileBox(this,"' + name + '") type="text" thumb="' + thumb + '" path="' + path + '" exts="' + exts + '" name="' + name + '_current_num" lay-verType="msg" lay-verify="' + layVerify + '" lay-reqtext="' + layReqtext + '" placeholder="' + placeholder + '" autocomplete="off" class="layui-input upload multiFile_' + name + '"></div>';
        addHtml += '</div>';

        addHtml = encodeURIComponent(addHtml);

        if (isEmpty(value)) {
            var html = '<div id="' + name + '_box">';
            html += '<input type="hidden" id="' + name + '_total" value="1">';
            html += '<input type="hidden" name="' + name + '" value="">';
            html += '<div style="display: -webkit-flex;display: flex;width:100%;position: relative;" id="' + name + '_box_1">';
            html += '<div onclick=addUploadBox("' + addHtml + '","' + name + '") style="display: -webkit-flex;display: flex;width:auto;line-height:38px;padding-right:10px;"><button type="button" style="height:38px;width:38px;padding:0px;text-align:center" class="layui-btn layui-btn-normal">+</button></div>';
            html += '<div style="display: -webkit-flex;display: flex;flex:1;"><input type="text" onclick=openUploadFileBox(this,"' + name + '") thumb="' + thumb + '" path="' + path + '" exts="' + exts + '" name="' + name + '_1" lay-verType="msg" lay-verify="' + layVerify + '" lay-reqtext="' + layReqtext + '" placeholder="' + placeholder + '" autocomplete="off" class="layui-input upload multiFile_' + name + '"></div>';
            html += '</div>';
            html += '</div>';
        } else {
            var valueArr = value.split(",");
            var total = valueArr.length;
            var html = '<div id="' + name + '_box">';
            html += '<input type="hidden" id="' + name + '_total" value="' + total + '">';
            html += '<input type="hidden" name="' + name + '" value="' + value + '">';
            for (var i = 0; i < valueArr.length; i++) {
                var index = i + 1;
                if (i == 0) {
                    html += '<div style="display: -webkit-flex;display: flex;width:100%;position: relative;" id="' + name + '_box_' + index + '">';
                    html += '<div onclick=addUploadBox("' + addHtml + '","' + name + '") style="display: -webkit-flex;display: flex;width:auto;line-height:38px;padding-right:10px;"><button type="button" style="height:38px;width:38px;padding:0px;text-align:center" class="layui-btn layui-btn-normal">+</button></div>';
                    html += '<div style="display: -webkit-flex;display: flex;flex:1;"><input value="' + valueArr[i] + '" type="text" onclick=openUploadFileBox(this,"' + name + '") thumb="' + thumb + '" path="' + path + '" exts="' + exts + '" name="' + name + '_' + index + '" lay-verType="msg" lay-verify="' + layVerify + '" lay-reqtext="' + layReqtext + '" placeholder="' + placeholder + '" autocomplete="off" class="layui-input upload multiFile_' + name + '"></div>';
                    html += '</div>';
                } else {
                    html += '<div style="display: -webkit-flex;display: flex;margin-top:10px;width:100%;position: relative;" id="' + name + '_box_' + index + '">';
                    html += '<div onclick=delUploadBox(this,"' + name + '") style="display: -webkit-flex;display: flex;width:auto;line-height:38px;padding-right:10px;"><button type="button" style="height:38px;width:38px;padding:0px;text-align:center" class="layui-btn layui-btn-danger">-</button></div>';
                    html += '<div style="display: -webkit-flex;display: flex;flex:1;"><input value="' + valueArr[i] + '" type="text" onclick=openUploadFileBox(this,"' + name + '") thumb="' + thumb + '" path="' + path + '" exts="' + exts + '" name="' + name + '_' + index + '" lay-verType="msg" lay-verify="' + layVerify + '" lay-reqtext="' + layReqtext + '" placeholder="' + placeholder + '" autocomplete="off" class="layui-input upload multiFile_' + name + '"></div>';
                    html += '</div>';
                }
            }
            html += '</div>';
        }

        $(this).html(html);
        $('.multiFile_' + name + '').blur(function() {
            // $("input[name='country']").val();
            var valArr = [];
            $(".multiFile_" + name).each(function(index, obj) {
                var val = $(this).val();
                valArr.push(val);
            });
            $("input[name='" + name + "']").val(valArr);
        });
    });


    //遍历所有多附件上传信息
    $(".multiFileRemarks").each(function(index, obj) {
        var thumb = $(this).attr("thumb") || "";
        var path = $(this).attr("path") || "";
        var exts = $(this).attr("exts") || "";
        var name = $(this).attr("name") || "";
        var layVerify = $(this).attr("lup-lay-verify") || "";
        var layReqtext = $(this).attr("lay-reqtext") || "";
        var placeholder = $(this).attr("placeholder") || "请上传...";
        var value = $(this).attr("value") || "";

        var addHtml = '<div style="display: -webkit-flex;display: flex;margin-top:10px;position: relative;" id="' + name + '_box_current_num">';
        addHtml += '<div onclick=delUploadBox(this,"' + name + '") style="display: -webkit-flex;display: flex;width:auto;line-height:38px;padding-right:10px;"><button type="button" style="height:38px;width:38px;padding:0px;text-align:center" class="layui-btn layui-btn-danger">-</button></div>';
        addHtml += '<div style="display: -webkit-flex;display: flex;width: 40%;min-width: 100px;position: relative;"><input no="current_num" ori-name="' + name + '" onclick=openUploadFileBox(this,"' + name + '") type="text" thumb="' + thumb + '" path="' + path + '" exts="' + exts + '" name="' + name + '_current_num_file" lay-verType="msg" lay-verify="' + layVerify + '" lay-reqtext="' + layReqtext + '" placeholder="' + placeholder + '" autocomplete="off" class="layui-input upload multiFileRemarks_file"></div>';
        addHtml += '<div style="display: -webkit-flex;display: flex;flex: 1;min-width: 100px;padding-left: 10px;"><input no="current_num" ori-name="' + name + '" type="text" thumb="' + thumb + '" path="' + path + '" exts="' + exts + '" name="' + name + '_current_num_remarks"  placeholder="No.current_num、请输入描述" autocomplete="off" class="layui-input multiFileRemarks_remarks"></div>';
        addHtml += '</div>';
        addHtml = encodeURIComponent(addHtml);

        if (isEmpty(value)) {
            var html = '<div id="' + name + '_box">';
            html += '<input type="hidden" id="' + name + '_total" value="1">';
            html += '<textarea style="display:none" name="' + name + '"></textarea>';
            html += '<div style="display: -webkit-flex;display: flex;width:100%;position: relative;" id="' + name + '_box_1">';
            html += '<div onclick=addUploadBox("' + addHtml + '","' + name + '") style="display: -webkit-flex;display: flex;width:auto;line-height:38px;padding-right:10px;"><button type="button" style="height:38px;width:38px;padding:0px;text-align:center" class="layui-btn layui-btn-normal">+</button></div>';
            html += '<div style="display: -webkit-flex;display: flex;width: 40%;min-width: 100px;position: relative;"><input no="1" ori-name="' + name + '" type="text" onclick=openUploadFileBox(this,"' + name + '") thumb="' + thumb + '" path="' + path + '" exts="' + exts + '" name="' + name + '_1_file" lay-verType="msg" lay-verify="' + layVerify + '" lay-reqtext="' + layReqtext + '" placeholder="' + placeholder + '" autocomplete="off" class="layui-input upload multiFileRemarks_file"></div>';
            html += '<div style="display: -webkit-flex;display: flex;flex: 1;min-width: 100px;padding-left: 10px;"><input no="1" ori-name="' + name + '" type="text" thumb="' + thumb + '" path="' + path + '" exts="' + exts + '" name="' + name + '_1_remarks"  placeholder="No.1、请输入描述" autocomplete="off" class="layui-input multiFileRemarks_remarks"></div>';

            html += '</div>';
            html += '</div>';
        } else {
            value = decodeURIComponent(value);
            var valueArr = eval("(" + value + ")");
            var total = valueArr.length;
            var html = '<div id="' + name + '_box">';
            html += '<input type="hidden" id="' + name + '_total" value="' + total + '">';
            html += '<textarea style="display:none" name="' + name + '">' + value + '</textarea>';
            for (var i = 0; i < valueArr.length; i++) {
                var index = i + 1;
                if (i == 0) {
                    html += '<div style="display: -webkit-flex;display: flex;width:100%;position: relative;" id="' + name + '_box_' + index + '">';
                    html += '<div onclick=addUploadBox("' + addHtml + '","' + name + '") style="display: -webkit-flex;display: flex;width:auto;line-height:38px;padding-right:10px;"><button type="button" style="height:38px;width:38px;padding:0px;text-align:center" class="layui-btn layui-btn-normal">+</button></div>';
                    html += '<div style="display: -webkit-flex;display: flex;width: 40%;min-width: 100px;position: relative;"><input no="1" ori-name="' + name + '" value="' + valueArr[i].url + '" type="text" onclick=openUploadFileBox(this,"' + name + '") thumb="' + thumb + '" path="' + path + '" exts="' + exts + '" name="' + name + '_' + index + '_file" lay-verType="msg" lay-verify="' + layVerify + '" lay-reqtext="' + layReqtext + '" placeholder="' + placeholder + '" autocomplete="off" class="layui-input upload multiFileRemarks_file"></div>';
                    html += '<div style="display: -webkit-flex;display: flex;flex: 1;min-width: 100px;padding-left: 10px;"><input no="1" ori-name="' + name + '" value="' + valueArr[i].remarks + '" type="text" thumb="' + thumb + '" path="' + path + '" exts="' + exts + '" name="' + name + '_1_remarks"  placeholder="No.1、请输入描述" autocomplete="off" class="layui-input multiFileRemarks_remarks"></div>';
                    html += '</div>';
                } else {
                    html += '<div style="display: -webkit-flex;display: flex;margin-top:10px;width:100%;position: relative;" id="' + name + '_box_' + index + '">';
                    html += '<div onclick=delUploadBox(this,"' + name + '") style="display: -webkit-flex;display: flex;width:auto;line-height:38px;padding-right:10px;"><button type="button" style="height:38px;width:38px;padding:0px;text-align:center" class="layui-btn layui-btn-danger">-</button></div>';
                    html += '<div style="display: -webkit-flex;display: flex;width: 40%;min-width: 100px;position: relative;"><input no="' + index + '" ori-name="' + name + '" value="' + valueArr[i].url + '" type="text" onclick=openUploadFileBox(this,"' + name + '") thumb="' + thumb + '" path="' + path + '" exts="' + exts + '" name="' + name + '_' + index + '_file" lay-verType="msg" lay-verify="' + layVerify + '" lay-reqtext="' + layReqtext + '" placeholder="' + placeholder + '" autocomplete="off" class="layui-input upload multiFileRemarks_file"></div>';
                    html += '<div style="display: -webkit-flex;display: flex;flex: 1;min-width: 100px;padding-left: 10px;"><input no="' + index + '" ori-name="' + name + '" value="' + valueArr[i].remarks + '" type="text" thumb="' + thumb + '" path="' + path + '" exts="' + exts + '" name="' + name + '_' + index + '_remarks"  placeholder="No.' + index + '、请输入描述" autocomplete="off" class="layui-input multiFileRemarks_remarks"></div>';

                    html += '</div>';
                }
            }
            html += '</div>';
        }
        $(this).html(html);


    });
    multiFileRemarksListen();
    $(".singleFileRemarksValue").each(function(index, obj) {
        var name = $(this).attr("name");
        var val = $(this).val();
        if (isJSON(val)) {
            var json = eval('(' + val + ')');
            var file = json.url || "";
            var remarks = json.remarks || "";
            $("input[name='" + name + "_file']").val(file);
            $("input[name='" + name + "_remarks']").val(remarks);
        }

    });
    //遍历所有upload信息,此遍历需放在下面，否则图片不出来
    $(".upload").each(function(index, obj) {
        var fileUrl = $(this).val();
        var name = $(this).attr("name");
        if (fileUrl != "") {
            $("#" + name).remove();
            var ext = fileUrl.substring(fileUrl.lastIndexOf("."), fileUrl.length); //后缀名
            ext = ext.toLowerCase();
            if (ext == '.gif' || ext == '.jpg' || ext == '.jpeg' || ext == '.png' || ext == '.bmp') {
                var str = '';
                str += '<div id="' + name + '" style="position:absolute; display:block; top:1px;right:1px;">';
                str += '<img onclick=openImg("' + name + '") onerror=javascript:this.src="../../../images/imgonerror.jpg" style="height:36px;min-width:36px;background:#ffffff;border-left:1px solid #ededed" src="' + fileUrl + '">';
                str += '<i class="layui-icon layui-icon-close-fill" onclick=delImg("' + name + '") style="color:red;position:absolute;right:-10px;top:-10px;font-size:25px; z-index:99"></i>';
                str += '</div>';
                $(obj).parent().append(str);
            } else {
                var str = '';
                str += '<div id="' + name + '" style="position:absolute; display:block; top:1px;right:1px;">';
                str += '<img onclick=openFile("' + fileUrl + '") onerror=javascript:this.src="../../../images/imgonerror.jpg" style="height:36px;min-width:36px;background:#ffffff;border-left:1px solid #ededed" src="' + project_path + 'images/file.png">';
                str += '<i class="layui-icon layui-icon-close-fill" onclick=delImg("' + name + '") style="color:red;position:absolute;right:-10px;top:-10px;font-size:25px; z-index:99"></i>';
                str += '</div>';
                $(obj).parent().append(str);
            }
        }
    });

    $(".singleFileRemarks_remarks").bind("input propertychange", function() {
        var oriName = $(this).attr("ori-name");
        var remarks = $(this).val() || "";
        var file = $("input[name='" + oriName + "_file']").val() || "";
        var json = { url: file, remarks: remarks };
        if (remarks == "" && file == "") {
            $("textarea[name='" + oriName + "']").val("");
        } else {
            $("textarea[name='" + oriName + "']").val(JSON.stringify(json));
        }
    });

    $(".singleFileRemarks_file").bind("input propertychange", function() {
        var oriName = $(this).attr("ori-name");
        var file = $(this).val() || "";
        var remarks = $("input[name='" + oriName + "_remarks']").val() || "";
        var json = { url: file, remarks: remarks };
        // console.log(json);
        if (remarks == "" && file == "") {
            $("textarea[name='" + oriName + "']").val("");
        } else {
            $("textarea[name='" + oriName + "']").val(JSON.stringify(json));
        }
    });
}

function isJSON(str) {
    if (str == "") {
        return false;
    }
    if (typeof str == 'string') {
        try {
            var obj = JSON.parse(str);
            if (typeof obj == 'object' && obj) {
                return true;
            } else {
                return false;
            }

        } catch (e) {
            //console.log('error：' + str + '!!!' + e);
            return false;
        }
    }
}

function openImg(id) {
    layer.photos({
        photos: "#" + id,
        shade: 0.1,
        // anim: 5 //0-6的选择，指定弹出图片动画类型，默认随机（请注意，3.0之前的版本用shift参数）
    });
}

function delImg(id) {
    layer.confirm("确定要删除该附件吗？", function(index) {
        $("#" + id).remove();
        $("input[name='" + id + "']").val("");
        layer.msg("已删除");
    });
}

function openFile(file) {
    layer.confirm('路径(' + file + '，点击确定下载)', function(index) {
        window.open(file);
        layer.close(index);
        return false;
    });
}

function uploadSuccess(name, ret, fieldName) {
    var obj = $("input[name='" + name + "']");
    var msg = ret.msg;
    var code = ret.code;
    var fileUrl = ret.data.file_url;
    var fileOriName = ret.data.ori_name;
    var ext = fileUrl.substring(fileUrl.lastIndexOf("."), fileUrl.length); //后缀名
    obj.val(fileUrl);

    if (fieldName) {
        var valArr = [];
        $(".multiFile_" + fieldName).each(function(index, obj) {
            var val = $(this).val();
            valArr.push(val);
        });
        $("input[name='" + fieldName + "']").val(valArr);
    }
    $("#" + name).remove();
    ext = ext.toLowerCase();
    if (ext == '.gif' || ext == '.jpg' || ext == '.jpeg' || ext == '.png' || ext == '.bmp') {
        var str = '';
        str += '<div id="' + name + '" style="position:absolute; display:block; top:1px;right:1px;">';
        str += '<img onclick=openImg("' + name + '") onerror=javascript:this.src="../../../images/imgonerror.jpg" style="height:36px;min-width:36px;background:#ffffff;border-left:1px solid #ededed" src="' + fileUrl + '">';
        str += '<i class="layui-icon layui-icon-close-fill" onclick=delImg("' + name + '") style="color:red;position:absolute;right:-10px;top:-10px;font-size:25px; z-index:99"></i>';
        str += '</div>';
        $(obj).parent().append(str);
    } else {
        //其他附件
        var str = '';
        str += '<div id="' + name + '" style="position:absolute; display:block; top:1px;right:1px;">';
        str += '<img onclick=openFile("' + fileUrl + '") onerror=javascript:this.src="../../../images/imgonerror.jpg" style="height:36px;min-width:36px;background:#ffffff;border-left:1px solid #ededed" src="' + project_path + 'images/file.png">';
        str += '<i class="layui-icon layui-icon-close-fill" onclick=delImg("' + name + '") style="color:red;position:absolute;right:-10px;top:-10px;font-size:25px; z-index:99"></i>';
        str += '</div>';
        $(obj).parent().append(str);
    }
    //监听是否带有描述的上传框
    var singleFileRemarksFileClass = obj.hasClass("singleFileRemarks_file") || false;
    if (singleFileRemarksFileClass) {
        var oriName = obj.attr("ori-name") || "";
        var file = obj.val() || "";
        // var remarks = $("input[name='" + oriName + "_remarks']").val() || "";
        var remarks = fileOriName;
        $("input[name='" + oriName + "_remarks']").val(remarks);
        var json = { url: file, remarks: remarks };
        if (remarks == "" && file == "") {
            $("textarea[name='" + oriName + "']").val("");
        } else {
            $("textarea[name='" + oriName + "']").val(JSON.stringify(json));
        }
    }

    //监听是否带有描述的上传框（多附件）

    var multiFileRemarksFileClass = obj.hasClass("multiFileRemarks_file") || false;
    if (multiFileRemarksFileClass) {
        var arr = [];
        var oriName = $(obj).attr("ori-name");
        var total = $("#" + oriName + "_total").val();
        //遍历所有的附件框
        for (var i = 1; i <= total; i++) {
            var file = $("input[name='" + oriName + "_" + i + "_file']").val() || "";
            if (file == fileUrl) {
                var remarks = fileOriName;
                $("input[name='" + oriName + "_" + i + "_remarks']").val(remarks);
            } else {
                var remarks = $("input[name='" + oriName + "_" + i + "_remarks']").val() || "";

            }
            if (remarks != "" || file != "") {
                var json = { url: file, remarks: remarks };
                arr.push(json);
            }
        }
        if (arr.length > 0) {
            $("textarea[name='" + oriName + "']").val(JSON.stringify(arr));

        } else {
            $("textarea[name='" + oriName + "']").val("");
        }
    }
}

function listUpload(id, fileUrl, customStr) {
    if (isEmpty(fileUrl)) {
        if (customStr) {
            return customStr;
        }
        return "";
    }
    if (fileUrl == "") {
        return customStr || "";
    }
    var fileUrlStr = "" + fileUrl + "";
    var _arrAlt = [];
    if (isJSON(fileUrl)) {
        var fileUrlJson = JSON.parse(fileUrl);
        if (!Array.isArray(fileUrlJson)) {
            fileUrlStr = fileUrlJson.url || "";
            _arrAlt[0] = fileUrlJson.remarks || "";
            fileUrl = fileUrlStr;
        } else {
            //json数组
            var _arr = [];
            for (var i = 0; i < fileUrlJson.length; i++) {
                _arr[i] = fileUrlJson[i].url;
                _arrAlt[i] = fileUrlJson[i].remarks;
            }
            fileUrlStr = _arr.join(",");
            fileUrl = fileUrlStr;
        }
    }

    fileUrlStrArr = fileUrlStr.split(",");
    if (fileUrlStrArr.length > 1) {
        var str = [];
        for (var j = 0; j < fileUrlStrArr.length; j++) {
            var alt = _arrAlt[j] || "";
            var ext = fileUrlStrArr[j].substring(fileUrlStrArr[j].lastIndexOf("."), fileUrlStrArr[j].length); //后缀名
            if (ext == '.jpg' || ext == '.png' || ext == '.jpeg' || ext == '.gif' || ext == '.bmp') {
                str.push("<img alt='" + alt + "' onerror=javascript:this.src='../../../images/imgonerror.jpg' onclick=openImg('" + id + "') src='" + fileUrlStrArr[j] + "' style='height:30px;min-width:30px;padding:0px;margin:0px;'>");
            } else {
                str.push("<img onclick=openFile('" + fileUrlStrArr[j] + "');return false;  style='height:30px;min-width:30px;padding:0px;margin:0px;color:#009688' src='../../../images/file.png'>");
            }
        }
        str = str.join(" ");
        str = "<span id='" + id + "'>" + str + "</span>";
    } else {

        var str = "";
        var alt = _arrAlt[0] || "";
        var ext = fileUrl.substring(fileUrl.lastIndexOf("."), fileUrl.length); //后缀名
        if (ext == '.jpg' || ext == '.png' || ext == '.jpeg' || ext == '.gif' || ext == '.bmp') {
            str += "<span id='" + id + "'><img alt='" + alt + "' onerror=javascript:this.src='../../../images/imgonerror.jpg' onclick=openImg('" + id + "') src='" + fileUrl + "' style='height:30px;min-width:30px;padding:0px;margin:0px;'></span>";
        } else {
            str += "<span id='" + id + "' onclick=openFile('" + fileUrl + "')><img style='height:30px;min-width:30px;padding:0px;margin:0px;color:#009688' src='../../../images/file.png'></span>";
        }

    }
    if (str == "" && customStr) {
        return customStr;
    }
    // console.log(str);
    return str;
}

function dateToTimestamp(timeDate, dataCheckType) {
    if (dataCheckType == 'timeMs') {
        return new Date(timeDate).getTime();
    } else if (dataCheckType == 'time') {
        return new Date(timeDate).getTime() / 1000;
    } else {
        return timeDate;
    }

}

function dateFormat(date) {
    if (date == '1970-01-01') {
        return "";
    } else if (date == '1970-01-01 08:00:00') {
        return "";
    } else {
        return date;
    }
}

function decodeEntities(encodedString) {
    var textArea = document.createElement('textarea');
    textArea.innerHTML = encodedString;
    return textArea.value;
}

function getCacheSize(t) {
    t = t == undefined ? "l" : t;
    var localData = {};
    var localTotal = 0;
    var localObj = "";
    var sessionData = {};
    var sessionTotal = 0;
    var sessionObj = "";
    if (!window.localStorage) {
        console.log('浏览器不支持localStorage');
    } else {
        localObj = window.localStorage;
        var size = 0;
        for (item in localObj) {
            if (localObj.hasOwnProperty(item)) {
                localData[item] = localObj.getItem(item);
                size += localObj.getItem(item).length;
            }
        }
        localTotal = (size / 1024).toFixed(2) + "KB";
    }
    if (!window.sessionStorage) {
        console.log('浏览器不支持sessionStorage');
    } else {
        sessionObj = window.sessionStorage;
        var size = 0;
        for (item in sessionObj) {
            if (sessionObj.hasOwnProperty(item)) {
                sessionData[item] = sessionObj.getItem(item);

                size += sessionObj.getItem(item).length;
            }
        }
        sessionTotal = (size / 1024).toFixed(2) + "KB";
    }
    var ret = { localStore: { localTotal: localTotal, localData: localData }, sessionStore: { sessionTotal: sessionTotal, sessionData: sessionData } };
    return ret;
}

function isIdentityCodeValid(code) {
    var city = { 11: "北京", 12: "天津", 13: "河北", 14: "山西", 15: "内蒙古", 21: "辽宁", 22: "吉林", 23: "黑龙江 ", 31: "上海", 32: "江苏", 33: "浙江", 34: "安徽", 35: "福建", 36: "江西", 37: "山东", 41: "河南", 42: "湖北 ", 43: "湖南", 44: "广东", 45: "广西", 46: "海南", 50: "重庆", 51: "四川", 52: "贵州", 53: "云南", 54: "西藏 ", 61: "陕西", 62: "甘肃", 63: "青海", 64: "宁夏", 65: "新疆", 71: "台湾", 81: "香港", 82: "澳门", 91: "国外 " };
    var tip = "";
    var pass = true;

    if (!code || !/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[12])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i.test(code)) {
        tip = "身份证号格式错误";
        pass = false;
    } else if (!city[code.substr(0, 2)]) {
        tip = "地址编码错误";
        pass = false;
    } else {
        // 18位身份证需要验证最后一位校验位
        if (code.length == 18) {
            code = code.split('');
            // ∑(ai×Wi)(mod 11)
            // 加权因子
            var factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
            // 校验位
            var parity = [1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2];
            var sum = 0;
            var ai = 0;
            var wi = 0;
            for (var i = 0; i < 17; i++) {
                ai = code[i];
                wi = factor[i];
                sum += ai * wi;
            }
            var last = parity[sum % 11];
            if (parity[sum % 11] != code[17]) {
                tip = "校验位错误";
                pass = false;
            }
        }
    }
    return pass;
}